<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="虚拟商品" prop="isVirtual">
        <el-select
          v-model="queryParams.isVirtual"
          placeholder="请选择是否是虚拟商品"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in isVirtualOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goods:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:goods:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-dropdown class="filter-item">
          <el-button size="mini" type="primary"
            >批量上下架<i class="el-icon-arrow-down el-icon--right"></i
          ></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="tobatchup()"
              >批量上架</el-dropdown-item
            >
            <el-dropdown-item @click.native="tobatchdown()"
              >批量下架</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品图片" width="80">
        <template slot-scope="scope"
          ><a :href="scope.row.visitUrl" target="_blank">
            <img :src="scope.row.url" width="50" height="50"/></a
        ></template>
      </el-table-column>
      <el-table-column label="型号">
        <template slot-scope="scope">
          {{ skusNameComputed(scope.row.skus) }}
        </template>
      </el-table-column>
      <el-table-column label="零售价">
        <template slot-scope="scope">{{ scope.row.price.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column
        label="抵扣价"
        align="center"
        prop="offsettingPrice"
      ></el-table-column>
      <el-table-column label="进货价" align="center" prop="purchasePrice" />
      <el-table-column
        label="预估收益"
        align="center"
        prop="estimatedRevenue"
      />
      <el-table-column label="已售" align="center" prop="goodsRealSold" />
      <el-table-column
        label="好评率"
        align="center"
        prop="approvalRealRating"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column
        label="上架状态"
        align="center"
        prop="shelvesStatus"
        :formatter="shelvesStatusFormat"
      />
      <el-table-column
        label="虚拟商品"
        align="center"
        prop="isVirtual"
        :formatter="isVirtualFormat"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goods:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  updateShelvesStatus,
  exportGoods
} from "@/api/goods/goods";

export default {
  name: "Goods",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      goodsList: [],
      title: "",
      // 审核状态  0 审核通过 1 审核未通过 2 审核中字典
      statusOptions: [],
      // 商品上架状态 0 下架  1上架 2违规下架 默认0字典
      shelvesStatusOptions: [],
      // 是否是虚拟商品 0 否 1 是默认0字典
      isVirtualOptions: [],
      queryParams: {
        pageNum: 0,
        pageSize: 10,
        name: undefined,
        storeFcateId: undefined,
        storeScateId: undefined,
        storeTcateId: undefined,
        commissionRate: undefined,
        sCommissionRate: undefined,
        status: undefined,
        isVirtual: undefined
      },
      form: {},
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        storeId: [
          {
            required: true,
            message: "商品的店铺id 如果是平台的则为0 不能为空",
            trigger: "blur"
          }
        ],
        typeId: [
          { required: true, message: "类型id不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "品牌id不能为空", trigger: "blur" }
        ],
        delFlag: [
          {
            required: true,
            message: "删除标记   0未删除 1删除 默认0不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("audit_thress").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("goods_publish").then(response => {
      this.shelvesStatusOptions = response.data;
    });
    this.getDicts("ye_no01").then(response => {
      this.isVirtualOptions = response.data;
    });
  },
  computed: {
    skusNameComputed() {
      return function(skus) {
        var nameArr = [];
        skus.forEach(item => {
          nameArr.push(item.name);
        });
        if (nameArr.length > 0) {
          console.log(nameArr.join(","));
          return nameArr.join(",");
        } else {
          console.log("空");
          return "";
        }
      };
    }
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商品上架状态 0 下架  1上架 2违规下架 默认0字典翻译
    shelvesStatusFormat(row, column) {
      return this.selectDictLabel(this.shelvesStatusOptions, row.shelvesStatus);
    },
    // 是否是虚拟商品 0 否 1 是默认0字典翻译
    isVirtualFormat(row, column) {
      return this.selectDictLabel(this.isVirtualOptions, row.isVirtual);
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        subtitle: undefined,
        price: undefined,
        pcDesc: undefined,
        mobileDesc: undefined,
        seoTitle: undefined,
        seoKeywords: undefined,
        seoDesc: undefined,
        storeId: undefined,
        firstCateId: undefined,
        secondCateId: undefined,
        thirdCateId: undefined,
        typeId: undefined,
        brandId: undefined,
        storeFcateId: undefined,
        storeScateId: undefined,
        storeTcateId: undefined,
        url: undefined,
        delFlag: undefined,
        createName: undefined,
        modifyName: undefined,
        delName: undefined,
        createTime: undefined,
        modifyTime: undefined,
        delTime: undefined,
        commissionRate: undefined,
        sCommissionRate: undefined,
        status: undefined,
        shelvesStatus: undefined,
        isVirtual: undefined,
        video: undefined,
        videoPic: undefined,
        logisticsTemplateId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 0;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$router.push({ path: "/goods/goodsManager/addgoods" });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.$router.push({ path: "/goods/updatespu", query: { id: id } });
    },
    // 更新上下架状态
    updateShelvesStatus(ids, status) {
      if (this.isProcess) {
        return;
      }
      this.isProcess = true;
      updateShelvesStatus(ids, status).then(() => {
        this.isProcess = false;
        this.selectedIds = [];
        if (status == "0") {
          this.$message({
            type: "success",
            message: "批量下架成功!"
          });
        } else {
          this.$message({
            type: "success",
            message: "批量上架成功!"
          });
        }
        this.getList();
      });
    },
    tobatchup() {
      if (!this.ids || this.ids == 0) {
        this.$message({
          type: "error",
          message: "请至少选择一条记录!"
        });
        return;
      }
      this.$confirm("确定要上架选中的商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.updateShelvesStatus(this.ids.toString(), "1");
      });
    },
    tobatchdown() {
      if (!this.ids || this.ids == 0) {
        this.$message({
          type: "error",
          message: "请至少选择一条记录!"
        });
        return;
      }
      this.$confirm("确定要下架选中的商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.updateShelvesStatus(this.ids.toString(), "0");
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delGoods(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有商品数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportGoods(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    }
  }
};
</script>
